var express = require('express');
var router = express.Router();

var moment = require('moment');

const { UsersModel } = require('../utils/model');
const { aesEncrypt } = require('../utils/index');  // 加密

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 注册接口
router.post('/register', function (req, res, next) {
  const body = req.body;
  // console.log(body);

  // 先判断数据库中是否已存在该数据，如果不存在则直接新增，如果存在则提示已注册
  UsersModel.findOne({
    $or: [
      { username: body.username },
      { phone: body.phone }
    ]
  })
    .then(data => {
      console.log(data,11111);
      if (data) {
        res.send(`<script>alert('注册失败，当前账号已被注册');location.href='/register';</script>`);
      } else {
        // 注册
        body.time = new Date()
        UsersModel.insertMany({
          ...body
        })
          .then(result => {
            res.send(`<script>alert('注册成功，请登录');location.href='/login?username=${aesEncrypt(body.username)}';</script>`);
          })
          .catch(err => {
            console.log(err);
            res.send(`<script>alert('注册失败，未知错误');location.href='/register';</script>`);
          })
      }
    })
});

// 登陆接口
router.post('/signin', function (req, res) {
  const body = req.body;
  UsersModel.findOne({
    $or: [
      { username: body.username },
      { phone: body.phone }
    ]
  })
    .then(result => {
      if (result) {
        console.log(result.password);
        console.log(body.password);
        if (result.password == body.password) {
          req.session.username = result.username;
          req.session.phone = result.phone;
          req.session.loginTime = moment().format('YYYY-MM-DD HH:mm:ss')
          res.redirect('/');  // 重定向
        } else {
          if (body.username) res.send(`<script>alert('登陆失败，用户名或密码错误！');location.href='/login';</script>`);
          if (body.phone) res.send(`<script>alert('登陆失败，手机号或密码错误！');location.href='/login';</script>`);
        }
      } else {
        if (body.username) res.send(`<script>alert('登陆失败，用户名不存在！');location.href='/login';</script>`);
        if (body.phone) res.send(`<script>alert('登陆失败，手机号不存在！');location.href='/login';</script>`);
      }
    })
    .catch(err => {
      console.log(err);
      res.send(`<script>alert('登陆失败，未知错误！');location.href='/login';</script>`);
    })
})

module.exports = router;
